package net.atomarrow.db.parser;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import net.atomarrow.configs.DbConfig;
import net.atomarrow.util.StringUtil;
/**
 * 值处理器
 * @author Michael
 *
 */
public class ValueProcessor {

	/**
	 * 处理字符串格式
	 * @param value
	 * @return
	 */
	public static Serializable processValue(Serializable value) {
		if(value instanceof Expression){
			value=processExpression((Expression)value);
		}else if (value instanceof String) {
			value = "'" +safeProcess(value)+ "'";
		} else if (value instanceof java.util.Date ||value instanceof java.sql.Date||value instanceof Timestamp) {
			java.util.Date d = (java.util.Date) value;
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			//根据不同数据库处理
			if(DbConfig.getDatabaseType().equals(DbConfig.DB_TYPE_MYSQL)){
				value = "'" + sf.format(d) + "'";
			}else if(DbConfig.getDatabaseType().equals(DbConfig.DB_TYPE_ORACLE)){
				value="to_date('"+sf.format(d)+"','yyyy-MM-dd hh24:mi:ss')";
			}
		} else if (value instanceof Enum) {
			return "'" + value + "'";
		}
		return value;
	}
	private static Serializable processExpression(Expression expression) {
		if(expression.getParams()==null){
			return "("+expression.getSql()+")";
		}else{
			StringBuilder sql=new StringBuilder(expression.getSql());
			sql.insert(0, "(");
			for(Serializable param:expression.getParams()){
				int index=sql.indexOf("?");
				if(index==-1){
					throw new RuntimeException(expression.getSql()+"参数数量错误");
				}
				sql.replace(index, index+1, processValue(param).toString());
			}
			if(sql.indexOf("?")!=-1){
				throw new RuntimeException(expression.getSql()+"参数数量错误");
			}
			sql.append(")");
			return sql.toString();
		}
	}
	
    protected static Serializable safeProcess(Serializable value){
        return StringUtil.replace(value.toString(), "'", "''").replace("\\", "\\\\");
    }
}
